package swing.swing02;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class JFileChooserDemo {
    //创建窗口
    JFrame fr=new JFrame("测试JFileChooser");

    //创建菜单条
    JMenuBar jmb=new JMenuBar();
    //创建caidan
    JMenu jMenu=new JMenu("文件");

    JMenuItem open=new JMenuItem(new AbstractAction("打开"){

        @Override
        public void actionPerformed(ActionEvent e) {
            // 显示一个文件选择器
            // .是相对路径 "md_00"
            JFileChooser fileChoose=new JFileChooser(".");
            fileChoose.showOpenDialog(fr);

            //获取用户选择的文件
            File file=fileChoose.getSelectedFile();

            // 进行显示
            try {
                image= ImageIO.read(file);
                drawArea.repaint();
            } catch (IOException ex) {
                ex.printStackTrace();
            }


        }
    });


    JMenuItem save =new JMenuItem(new AbstractAction("另存为"){
        @Override
        public void actionPerformed(ActionEvent e){
            //显示一个文件选择器
            JFileChooser fileChooser=new JFileChooser(".");
            fileChooser.showSaveDialog(fr);

            //获取用户选择的保存文件路径
            File file=fileChooser.getSelectedFile();

            try {
                ImageIO.write(image,"jpeg",file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    });

    BufferedImage image;

    private class MyCanvas extends JPanel{
        @Override
        public void paint(Graphics g){
            //把图片绘制到组件上即可

            g.drawImage(image,0,0,null);

        }
    }

    MyCanvas drawArea=new MyCanvas();

    public void init(){

        jMenu.add(open);
        jMenu.add(save);

        jmb.add(jMenu);
        fr.setJMenuBar(jmb);

        drawArea.setPreferredSize(new Dimension(740,500));
        fr.add(drawArea);


        // 显示fr
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.pack();
        fr.setVisible(true);

    }

    public static void main(String[] args){
        new JFileChooserDemo().init();
    }
}
